<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>JDBC | Cying</title><meta name="keywords" content="Java"><meta name="author" content="Cying-承影"><meta name="copyright" content="Cying-承影"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Cying, What&#39;s Mean JDBC    JDBC - (Java Database Connectivity)，是用于将 MySQL 连接到 Java 工程的开源 API  JDBC 主要结构  DriveManager - 作为链接到数据库的驱动存在 [好比移动&#x2F;联通&#x2F;电信] Connection - 是 Java 与 MySQL 的会话连接 [好比一次拨号成功] Prepare">
<meta property="og:type" content="article">
<meta property="og:title" content="JDBC">
<meta property="og:url" content="http://cyingk.github.io/2019/12/13/SQL_To_Java/index.html">
<meta property="og:site_name" content="Cying">
<meta property="og:description" content="Cying, What&#39;s Mean JDBC    JDBC - (Java Database Connectivity)，是用于将 MySQL 连接到 Java 工程的开源 API  JDBC 主要结构  DriveManager - 作为链接到数据库的驱动存在 [好比移动&#x2F;联通&#x2F;电信] Connection - 是 Java 与 MySQL 的会话连接 [好比一次拨号成功] Prepare">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20191213203223906.png">
<meta property="article:published_time" content="2019-12-12T17:04:19.000Z">
<meta property="article:modified_time" content="2020-02-15T18:16:12.000Z">
<meta property="article:author" content="Cying-承影">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20191213203223906.png"><link rel="shortcut icon" href="/img/favicon.ico"><link rel="canonical" href="http://cyingk.github.io/2019/12/13/SQL_To_Java/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.clarity.ms"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>(function(c,l,a,r,i,t,y){
    c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
    t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
    y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", "4zndahq92q");</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: 'days',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"Traditional Chinese Activated Manually","cht_to_chs":"Simplified Chinese Activated Manually","day_to_night":"Dark Mode Activated Manually","night_to_day":"Light Mode Activated Manually","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isanchor: false
};

const saveToLocal = {
  // ttl 單位是 天
  set: function setWithExpiry(key, value, ttl) {
    if (ttl === 0) return
    const now = new Date()
    const expiryDay = ttl * 86400000
    const item = {
      value: value,
      expiry: now.getTime() + expiryDay,
    }
    localStorage.setItem(key, JSON.stringify(item))
  },

  get: function getWithExpiry(key) {
    const itemStr = localStorage.getItem(key)

    if (!itemStr) {
      return undefined
    }
    const item = JSON.parse(itemStr)
    const now = new Date()

    if (now.getTime() > item.expiry) {
      localStorage.removeItem(key)
      return undefined
    }
    return item.value
  }
}

// https://stackoverflow.com/questions/16839698/jquery-getscript-alternative-in-native-javascript
const getScript = url => new Promise((resolve, reject) => {
  const script = document.createElement('script')
  script.src = url
  script.async = true
  script.onerror = reject
  script.onload = script.onreadystatechange = function() {
    const loadState = this.readyState
    if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
    script.onload = script.onreadystatechange = null
    resolve()
  }
  document.head.appendChild(script)
})</script><script id="config_change">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2020-02-16 02:16:12'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(function () {  window.activateDarkMode = function () {
    document.documentElement.setAttribute('data-theme', 'dark')
    if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
    }
  }
  window.activateLightMode = function () {
    document.documentElement.setAttribute('data-theme', 'light')
   if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
    }
  }
  const autoChangeMode = '1'
  const t = saveToLocal.get('theme')
  if (autoChangeMode === '1') {
    const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
    const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
    const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
    const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified
    if (t === undefined) {
      if (isLightMode) activateLightMode()
      else if (isDarkMode) activateDarkMode()
      else if (isNotSpecified || hasNoSupport) {
        const now = new Date()
        const hour = now.getHours()
        const isNight = hour <= 6 || hour >= 18
        isNight ? activateDarkMode() : activateLightMode()
      }
      window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
        if (saveToLocal.get('theme') === undefined) {
          e.matches ? activateDarkMode() : activateLightMode()
        }
      })
    } else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else if (autoChangeMode === '2') {
    const now = new Date()
    const hour = now.getHours()
    const isNight = hour <= 6 || hour >= 18
    if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
    else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else {
    if (t === 'dark') activateDarkMode()
    else if (t === 'light') activateLightMode()
  }const asideStatus = saveToLocal.get('aside-status')
if (asideStatus !== undefined) {
   if (asideStatus === 'hide') {
     document.documentElement.classList.add('hide-aside')
   } else {
     document.documentElement.classList.remove('hide-aside')
   }
}const fontSizeVal = saveToLocal.get('global-font-size')
if (fontSizeVal !== undefined) {
  document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
}})()</script><meta name="generator" content="Hexo 5.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">Loading...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="/img/avatar.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">23</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">12</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">Categories</div><div class="length-num">3</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> Categories</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://5b0988e595225.cdn.sohucs.com/images/20190831/84729f5c5bb346208416445feb485df6.jpeg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Cying</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> Categories</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">JDBC</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2019-12-12T17:04:19.000Z" title="Created 2019-12-13 01:04:19">2019-12-13</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2020-02-15T18:16:12.000Z" title="Updated 2020-02-16 02:16:12">2020-02-16</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Blog/">Blog</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">Word count:</span><span class="word-count">854</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">Reading time:</span><span>3min</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><html><head></head><body><p><a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/20191213203223906.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0N5aW5nSw==,size_16,color_FFFFFF,t_70" data-fancybox="group" data-caption="在这里插入图片描述" class="fancybox"><img alt="在这里插入图片描述" title="在这里插入图片描述" data-src="https://img-blog.csdnimg.cn/20191213203223906.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0N5aW5nSw==,size_16,color_FFFFFF,t_70" class="lazyload"></a></p>
<center><h1>Cying, What's Mean JDBC</h1></center>

<hr>
<blockquote>
<p><strong>JDBC</strong> - (<strong>Java Database Connectivity</strong>)，是用于将 <strong>MySQL</strong> 连接到 <strong>Java</strong> 工程的开源 <strong>API</strong></p>
</blockquote>
<h3 id="JDBC-主要结构"><a href="#JDBC-主要结构" class="headerlink" title="JDBC 主要结构"></a>JDBC 主要结构</h3><blockquote>
<ul>
<li><code>DriveManager</code> - 作为链接到数据库的驱动存在 [好比移动/联通/电信]</li>
<li><code>Connection</code> - 是 <strong>Java</strong> 与 <strong>MySQL</strong> 的会话连接 [好比一次拨号成功]</li>
<li><code>PrepareStatement</code> - 是 <strong>Java</strong> 向 <strong>MySQL</strong> 发出的请求 [<strong>Java</strong> 告诉 <strong>MySQL</strong> 要干嘛]</li>
<li><code>ResultSet</code> - <strong>MySQL</strong> 向 <strong>Java</strong> 返回的结果</li>
</ul>
</blockquote>
<h3 id="1-配置好驱动-DriverManager"><a href="#1-配置好驱动-DriverManager" class="headerlink" title="1.配置好驱动 DriverManager"></a>1.配置好驱动 <code>DriverManager</code></h3><ul>
<li>点击下载 <a href="https://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-5.1.48.zip" target="_blank" rel="noopener"><code>JDBC</code></a> 驱动器</li>
<li>解压后，在 <code>Java</code> 项目中引入 <code>mysql-connector-java-版本号.jar</code><br><br><a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/2019121321451754.png#pic_center" data-fancybox="group" data-caption="在这里插入图片描述" class="fancybox"><img alt="在这里插入图片描述" title="在这里插入图片描述" data-src="https://img-blog.csdnimg.cn/2019121321451754.png#pic_center" class="lazyload"></a></li>
</ul>
<hr>
<h3 id="2-封装一个-DriveManager"><a href="#2-封装一个-DriveManager" class="headerlink" title="2.封装一个 DriveManager"></a>2.封装一个 DriveManager</h3><blockquote>
<p>因为每次注册驱动的方法都是一样的，无非就是用户 <strong>MySQL</strong> 的用户名、密码、要连接的数据库名，其中只有一个 <strong>要连接的数据库名</strong> 会不一样，所以我们一般把注册驱动封装成一个独立的 <strong>X.Java</strong> 文件</p>
</blockquote>
<blockquote>
<p>如下所示，在 <strong>X.Java</strong> (名字随意，我这里是<strong>ConnectToMySQL.java</strong>) 中有一个 <strong>getConnection</strong> 的方法，返回的类型为 <strong>Connection</strong> </p>
<ul>
<li>返回的是 <strong>DriverManager.getConnection();</strong> ，其中有三个参数，一个分别是 <strong>URL</strong>，<strong>UserName</strong>，<strong>PassWord</strong></li>
<li><strong>UserName</strong> 和 <strong>PassWord</strong> 记得改成自己的数据库账号、密码</li>
<li><strong>URL</strong> 是数据库的连接地址，格式是固定的，只有中间的数据库名有变动，所以 <strong>URL</strong> 采用的字符串拼接方式，在拼接的时候就把传过来的数据库名加进去。</li>
</ul>
</blockquote>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.sql.Connection;</span><br><span class="line"><span class="keyword">import</span> java.sql.DriverManager;</span><br><span class="line"><span class="keyword">import</span> java.sql.SQLException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ConnectToMySQL</span> </span>{</span><br><span class="line"></span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">static</span> String username = <span class="string">"****"</span>;</span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">static</span> String password = <span class="string">"****"</span>;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Connection <span class="title">getConnection</span><span class="params">(String dataBaseName)</span> <span class="keyword">throws</span> SQLException </span>{</span><br><span class="line"></span><br><span class="line">    String url = <span class="string">"jdbc:mysql://localhost:3306/"</span> + dataBaseName + <span class="string">"?useSSL=false&serverTimezone=UTC&charset=utf8"</span>;</span><br><span class="line">    <span class="keyword">return</span> DriverManager.getConnection(url,username,password);</span><br><span class="line"></span><br><span class="line">  }</span><br><span class="line"></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<hr>
<h3 id="3-测试连接"><a href="#3-测试连接" class="headerlink" title="3.测试连接"></a>3.测试连接</h3><blockquote>
<ul>
<li>声明 <strong>Connection</strong></li>
<li>声明 <strong>PreparedStatement</strong></li>
<li>根据封装的 <strong>ConnectToMySQL</strong> 获取会话连接 <strong>connection</strong></li>
<li>对会话传输指令 <strong>preparedStatement</strong></li>
<li>执行 <strong>preparedStatement</strong> 的指令</li>
<li>关闭 <strong>Connection</strong> 和 <strong>PreparedStatement</strong>，先打开的后关闭，后打开的先关闭</li>
</ul>
</blockquote>
<div class="code-area-wrap"><div class="highlight-tools"><i class="fa fa-angle-down code-expand" aria-hidden="true"></i><div class="code_lang">java</div></div><figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.sql.Connection;</span><br><span class="line"><span class="keyword">import</span> java.sql.PreparedStatement;</span><br><span class="line"><span class="keyword">import</span> java.sql.ResultSet;</span><br><span class="line"><span class="keyword">import</span> java.sql.SQLException;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">T_JDBC</span> </span>{</span><br><span class="line"></span><br><span class="line">  <span class="keyword">static</span> Connection connection = <span class="keyword">null</span>;</span><br><span class="line">  <span class="keyword">static</span> PreparedStatement pStatement = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> SQLException </span>{</span><br><span class="line"></span><br><span class="line">    connection = ConnectToMySQL.getConnection(<span class="string">"T_JDBC"</span>);  <span class="comment">// 连接数据库 T_JDBC</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 下面两句是查询部分，具体查询代码在 doQuery 方法中</span></span><br><span class="line">    System.out.printf(<span class="string">"第一次查询："</span>);</span><br><span class="line">    doQuery(<span class="string">"SELECT * FROM USER"</span>);  </span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    跳转至 doQuery()，并把 "SELECT * FROM USER" 传过去</span></span><br><span class="line"><span class="comment">    User 是我在数据库 T_JDBC 中新建的表，有 </span></span><br><span class="line"><span class="comment">    NAME VARCHAR(20)</span></span><br><span class="line"><span class="comment">    ID VARCHAR(20) </span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">// 下面四句是向数据库中写入数据</span></span><br><span class="line">    pStatement = connection.prepareStatement(<span class="string">"INSERT INTO USER VALUES (?,?)"</span>);  </span><br><span class="line">    <span class="comment">/* </span></span><br><span class="line"><span class="comment">    向 USER 表中添加数据，数据暂时用 ? 代替，避免出现 bug</span></span><br><span class="line"><span class="comment">    这里有几个 ? 是根据要修改的额表的字段具体情况来定</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    pStatement.setString(<span class="number">1</span>, <span class="string">"Kevin"</span>);  <span class="comment">// 设置第一个 ? 的值</span></span><br><span class="line">    pStatement.setString(<span class="number">2</span>, <span class="string">"2019****"</span>);  <span class="comment">// 设置第二个 ? 的值</span></span><br><span class="line">    pStatement.executeUpdate();  <span class="comment">// 执行更新</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">// 下面两句是查询部分，具体查询代码在 doQuery 方法中</span></span><br><span class="line">    System.out.printf(<span class="string">"第二次查询："</span>);  </span><br><span class="line">    doQuery(<span class="string">"SELECT * FROM USER"</span>);  </span><br><span class="line"></span><br><span class="line">    pStatement.close();</span><br><span class="line">    connection.close();   </span><br><span class="line">    <span class="comment">// 关闭 - 关闭顺序为从最后打开的，关到最开始打开的</span></span><br><span class="line">    </span><br><span class="line">  }</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">doQuery</span><span class="params">(String query)</span> <span class="keyword">throws</span> SQLException </span>{</span><br><span class="line"></span><br><span class="line">    pStatement = connection.prepareStatement(query);  <span class="comment">// 告诉会话 connection 要准备执行 query，其中 query 中存放的是传递过来的指令</span></span><br><span class="line">    ResultSet rSet = pStatement.executeQuery();  <span class="comment">// pStatement.executeQuery()是执行查询，这样就能的到查询的结果了，然后把结果放到 rSet 中</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span>(rSet.next()){  <span class="comment">// 遍历 rSet ，每个 rSet.next() 跳一行，而且第一次取值之前必须执行一次 rSet,next()，否则报错</span></span><br><span class="line">      String records = rSet.getString(<span class="number">1</span>) + <span class="string">"    \t"</span> + rSet.getString(<span class="number">2</span>);  <span class="comment">// rSet.getString 中放表的某个字段的序号</span></span><br><span class="line">      System.out.println(records);</span><br><span class="line">    }</span><br><span class="line">  }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div>

<hr>
<center><h2>运行结果如下所示</h2></center>

<p><a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/20191213223729506.png#pic_center" data-fancybox="group" data-caption="在这里插入图片描述" class="fancybox"><img alt="在这里插入图片描述" title="在这里插入图片描述" data-src="https://img-blog.csdnimg.cn/20191213223729506.png#pic_center" class="lazyload"></a></p>
<hr>
<center><h2>数据库情况如下所示</h2></center>

<p><a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/2019121322414471.png#pic_center" data-fancybox="group" data-caption="在这里插入图片描述" class="fancybox"><img alt="在这里插入图片描述" title="在这里插入图片描述" data-src="https://img-blog.csdnimg.cn/2019121322414471.png#pic_center" class="lazyload"></a></p>
<hr>
<center><h1 style="border: 1px solid grey">Finish</h1></center>

<hr>
</body></html></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="mailto:undefined">Cying-承影</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="http://cyingk.github.io/2019/12/13/SQL_To_Java/">http://cyingk.github.io/2019/12/13/SQL_To_Java/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/">Java</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2019/12/21/Network/"><img class="prev-cover" src="http://img.taopic.com/uploads/allimg/1305" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">Network</div></div></a></div><div class="next-post pull-right"><a href="/2019/12/12/What_Is_TypeScript/"><img class="next-cover" src="https://img-blog.csdnimg.cn/20191212214332469.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">What's TypeScript</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> Related Articles</span></div><div class="relatedPosts-list"><div><a href="/2020/02/26/UML/" title="UML"><img class="cover" src="https://upload-images.jianshu.io/upload_images/5336514-985132f6977c5d33.png?imageMogr2/auto-orient/strip|imageView2/2/w/694/format/webp" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-02-26</div><div class="title">UML</div></div></a></div><div><a href="/2020/01/16/Design_Pattern/" title="Design Pattern"><img class="cover" src="https://www.runoob.com/wp-content/uploads/2014/08/the-relationship-between-design-patterns.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-01-16</div><div class="title">Design Pattern</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">1.</span> <span class="toc-text">Cying, What&#39;s Mean JDBC</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#JDBC-%E4%B8%BB%E8%A6%81%E7%BB%93%E6%9E%84"><span class="toc-number">1.0.1.</span> <span class="toc-text">JDBC 主要结构</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E9%85%8D%E7%BD%AE%E5%A5%BD%E9%A9%B1%E5%8A%A8-DriverManager"><span class="toc-number">1.0.2.</span> <span class="toc-text">1.配置好驱动 DriverManager</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%B0%81%E8%A3%85%E4%B8%80%E4%B8%AA-DriveManager"><span class="toc-number">1.0.3.</span> <span class="toc-text">2.封装一个 DriveManager</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E6%B5%8B%E8%AF%95%E8%BF%9E%E6%8E%A5"><span class="toc-number">1.0.4.</span> <span class="toc-text">3.测试连接</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">1.1.</span> <span class="toc-text">运行结果如下所示</span></a></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">1.2.</span> <span class="toc-text">数据库情况如下所示</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">2.</span> <span class="toc-text">Finish</span></a></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="footer_custom_text">却道天凉好个秋</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="Increase font size"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="Decrease font size"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script></div><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>